<template>
  <div id="userLoginPage">
    <h1 class="title">用户登录</h1>
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
      @finish="handleSubmit"
      style="max-width: 500px; margin: 0 auto"
      label-align="left"
    >
      <a-form-item
        label="账号"
        name="userAccount"
        :rules="[
          { required: true, message: '请输入账号' },
          { min: 4, message: '用户账号过短' },
        ]"
      >
        <a-input
          v-model:value="formState.userAccount"
          placeholder="请输入账号"
        />
      </a-form-item>

      <a-form-item
        label="密码 "
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 4, message: '用户密码过短' },
        ]"
      >
        <a-input-password
          v-model:value="formState.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 4, span: 26 }">
        <a-button type="primary" html-type="submit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { userLogin } from "@/api/user";
import { message } from "ant-design-vue";
import { useLoginUserStore } from "@/store/user";
import { useRouter } from "vue-router";

const loginUserStore = useLoginUserStore();
const router = useRouter();

interface FormState {
  userAccount: string;
  userPassword: string;
}

const formState = reactive<FormState>({
  userAccount: "",
  userPassword: "",
});
const handleSubmit = async (values: any) => {
  const res = await userLogin(formState);
  if (res.data.code === 0 && res.data.data) {
    message.success("登陆成功");
    //将用户信息存放入登录态中
    loginUserStore.fetchLoginUser();
    //登录成功后转向首页
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("登录失败");
  }
};
</script>
<style scoped>
#userLoginPage .title {
  text-align: center;
  margin: 40px 0px;
}
</style>
